<script setup lang="ts">
defineOptions({
  name: "fabBoardEchartsModelBoxItemDialog"
});

import { ref, defineAsyncComponent, onMounted } from "vue";
import { useInitLineEcharts } from "./fabBoardSpcModelBoxItemEchartsHooks";
import { getFabBoardOneDayData, getFabBoardOneDayAreaData } from "@/api/modules/fab";

const echartsCom = defineAsyncComponent(() => import("@/views/common/components/echartsCom/index.vue"));

const echartsComRef = ref<InstanceType<typeof echartsCom> | null>(null);

const props = withDefaults(
  defineProps<{
    type?: number; //  0 所有机台当天24小时用量统计  1 每个机台当天总用量统计
    materialCode?: string;
    areaCode?: string;
    date?: string;
    title?: string;
    unit?: string;
  }>(),
  {
    type: 0,
    materialCode: "",
    areaCode: "",
    date: "",
    title: "",
    unit: ""
  }
);

const dialogVisible = defineModel({ type: Boolean, default: false });
const loading = ref<boolean>(false);

const echartsOptions = ref<CommonEcharts.CommonEchartsOption | null>(null);

const initFabBoardOneDayEchartsData = async (params: any) => {
  const res = await getFabBoardOneDayData(params, () => {
    loading.value = false;
  });
  useInitLineEcharts(2, [], props.title, props.unit, res, async data => {
    echartsOptions.value = data;
    await echartsComRef.value?.updateOption(true);
  });
};

const initFabBoardOneDayAreaEchartsData = async (params: any) => {
  const res = await getFabBoardOneDayAreaData(params, () => {
    loading.value = false;
  });
  useInitLineEcharts(3, [], props.title, props.unit, res, async data => {
    echartsOptions.value = data;
    await echartsComRef.value?.updateOption(true);
  });
};

const init = async () => {
  loading.value = true;
  const { materialCode = "", areaCode = "", date = "" } = props;
  // 调试
  // const params = { materialCode: "EL01IL01AV01", date: "20241214" };
  let params = null;
  switch (props.type) {
    case 0:
      params = { materialCode, areaCode, date };
      await initFabBoardOneDayEchartsData(params);
      break;
    case 1:
      params = { materialCode, areaCode };
      await initFabBoardOneDayAreaEchartsData(params);
      break;
  }
  loading.value = false;
};

onMounted(async () => {
  await init();
});
</script>

<template>
  <px-dialog v-model="dialogVisible" :title="title" width="1200px">
    <Suspense>
      <template #fallback>
        <div v-loading="true" class="echarts-fallback" />
      </template>
      <template #default>
        <div v-loading="loading" class="echarts-content">
          <echartsCom ref="echartsComRef" :options="echartsOptions" />
        </div>
      </template>
    </Suspense>
  </px-dialog>
</template>

<style lang="scss" scoped>
.echarts-content {
  height: 500px;
}
</style>
